ASP .Net Core动态注册中间件

改错

我在之前的文章ASP .Net Core实现动态文件服务器中的有些内容是错误的,这篇文章主要也是为了纠正其中的内容。

有三个错误:

  1. 我在那篇文章里说

很可惜,这些个是不能够动态设定的,也就是这些设置必须在apiApp.RunAsync()之前设定,启动之后再设置就没用了。但是如果按默认的设定,把apiApp停了整个服务就会挂掉,没法走设定后重启的路线,因此得在主应用之下加一个寄生应用作为文件服务的专有应用。

这个说法也对也不对,在app.Run()之后确实没法加入新的中间件了,ASP .Net Core管道中的中间件是有顺序的,app.Run()不接收next参数,也就是在之后加入的中间件是怎么也不会通过的。不对的地方在于实际上是可以通过((IApplicationBuilder)app).New()来新建一个拥有一模一样的管道,来替换掉原来的管道的,新建之后加入需要的中间件然后Run,就可以了。

  1. 我上篇文章开启服务用的方法是UseStaticFiles和UseDirectoryBrowser,这也不能说错,但是不够简洁,实际上ASP .Net Core除了提供UseStaticFiles和UseDirectoryBrowser,还提供了一个综合两者的功能UseFileServer,使用方法如下:
var fileServerOption = new FileServerOptions();
fileServerOption.RequestPath = urlPath;
fileServerOption.FileProvider = new PhysicalFileProvider(physicalPath);
fileServerOption.StaticFileOptions.ServeUnknownFileTypes = true;
fileServerOption.EnableDirectoryBrowsing = true;
app.UseFileServer(fileServerOption);
  1. 还有最最最大一个错误,我在之前的文章里是使用新端口另开服务来实现的,使用dotnet命令不指定端口号启动应用时没有问题,但当指定端口号或者使用IIS这样的WEB容器来部署时就没法开启除配置之外的端口了。

中间件

讲Asp .Net Core中间件的文章蛮多的,官方文档也很详细,我简单说下,他的概念是应用收到网络请求后,会经过一系列处理,然后响应,这个流程就好像水流过自来水管一样,所以叫管道。中间各种处理流程就是中间件,通过app.Use()来注册,最后响应是用app.Run(),因此app.Run()算是管道的出口。还有一个app.Map(),是用来定义分支的,就好像自来水管的分叉,每个分支最终也要用app.Run()来定义出口。

app.Map()的使用方式大概是这样:

app.Map("/home", app=>{
app.Run(async context =>
{
await context.Response.WriteAsync("Home Page");
});
});

看形式还是蛮好理解的,分支其实针对不同路径的请求给与不同的响应,分支当然是可以多段的。上面也展示了app.Run(),做的也确实是响应的事情。再就是app.Use()的使用方式了:

app.Use(async (context, next) =>
{
// Do something
await next.Invoke();
});

看形式也比较高理解,我们在Use中可以对请求的context进行各种操作,然后通过next()或者await next.Invoke()把它交给下一个中间件。

其他的各种Use比如我们用到的UseFileServer,也都是内置的或者外置的扩展中间件。

动态注册中间件

在第一部分有提到可以用((IApplicationBuilder)app).New()的方式来创建一个新管道替换原有管道,所以需要创建一个中间件用来干这个事。

app.Use(async (context,next) => {
if (Global.MiddlewareAction != null)
{
var builder = ((IApplicationBuilder)app).New();
Global.MiddlewareAction(builder);
builder.Run(next);
await builder.Build()(context);
}
else
{
await next.Invoke(context);
}
})

其中Global.MiddlewareActioAction<IApplicationBuilder>类型的委托,在需要动态注册中间件的时候给其赋值:

[HttpPost]
public async Task<string> SetFileServerAsync(FileServerDto fileDto)
{
Global.MiddlewareAction = app =>
{

app.UseCors(options =>
{
options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
var fileServerOption = new FileServerOptions();
fileServerOption.RequestPath = fileDto.UrlPath;
fileServerOption.FileProvider = new PhysicalFileProvider(fileDto.PhysicalPath);
fileServerOption.StaticFileOptions.ServeUnknownFileTypes = true;
fileServerOption.EnableDirectoryBrowsing = true;
app.UseFileServer(fileServerOption);
};
return "success";
}

当Global.MiddlewareAction为空的时候直接交给下一个中间件,如果不为空,也就是表示需要动态注册中间件,则复制新管道,添加中间件,替换原管道。

当然上面这个做法非常原始和初级,我在微软Chris Ross的github上找到一个注册中间件的中间件示例

整合代码如下:

public static class MiddlewareInjectorExtensions
{
public static IApplicationBuilder UseMiddlewareInjector(this IApplicationBuilder builder, MiddlewareInjectorOptions options)
{
return builder.UseMiddleware<MiddlewareInjectorMiddleware>(builder.New(), options);
}
}

public class MiddlewareInjectorMiddleware
{
private readonly RequestDelegate _next;
private readonly IApplicationBuilder _builder;
private readonly MiddlewareInjectorOptions _options;
private RequestDelegate _subPipeline;

public MiddlewareInjectorMiddleware(RequestDelegate next, IApplicationBuilder builder, MiddlewareInjectorOptions options)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_builder = builder ?? throw new ArgumentNullException(nameof(builder));
_options = options ?? throw new ArgumentNullException(nameof(options));
}

public Task Invoke(HttpContext httpContext)
{
var injector = _options.GetInjector();
if (injector != null)
{
var builder = _builder.New();
injector(builder);
builder.Run(_next);
_subPipeline = builder.Build();
}

if (_subPipeline != null)
{
return _subPipeline(httpContext);
}

return _next(httpContext);
}
}

public class MiddlewareInjectorOptions
{
private Action<IApplicationBuilder> _injector;

public void InjectMiddleware(Action<IApplicationBuilder> builder)
{
Interlocked.Exchange(ref _injector, builder);
}

internal Action<IApplicationBuilder> GetInjector()
{
return Interlocked.Exchange(ref _injector, null);
}
}

使用是首先对MiddlewareInjectorOptions注册单例

builder.Services.AddSingleton<MiddlewareInjectorOptions>();

然后注册中间件

var injectorOptions = app.Services.GetService<MiddlewareInjectorOptions>();
app.UseMiddlewareInjector(injectorOptions);

最后在使用的时候

[HttpPost]
public async Task<string> SetFileServerAsync(FileServerDto fileDto)
{
_middlewareInjectorOptions.InjectMiddleware(app =>
{
app.UseCors(options =>
{
options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
var fileServerOption = new FileServerOptions();
fileServerOption.RequestPath = fileDto.UrlPath;
fileServerOption.FileProvider = new PhysicalFileProvider(fileDto.PhysicalPath);
fileServerOption.StaticFileOptions.ServeUnknownFileTypes = true;
fileServerOption.EnableDirectoryBrowsing = true;
app.UseFileServer(fileServerOption);
});
return "success";
}

大功告成,补完上一篇文章的漏洞。

加载评论框需要翻墙